package com.whlilong.jxc.editor.support;

import java.util.List;

import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.widgets.Composite;

import com.whlilong.jxc.listener.IEditorListener;
import com.whlilong.jxc.listener.IModifyListener;
import com.whlilong.jxc.model.Hsinfo;
import com.whlilong.jxc.sys.CnToSpellFirstChar;
import com.whlilong.jxc.sys.ExtentionInfo;

public class BussinessInfoTextKeyCellEditor extends TextCellEditor {
	
	protected IEditorListener listener;
	private int currentColumn;
	private String oldString;// 单元格初始值
	private IModifyListener modify;
	
	public BussinessInfoTextKeyCellEditor(Composite parent,
			IEditorListener listener, int column,
			IModifyListener modify) {
		super(parent,SWT.SINGLE);
		this.listener = listener;
		this.currentColumn =column;
		this.modify = modify;
	}
		
		public void releaseKey() {
			fireApplyEditorValue();
			deactivate();
		}

		@Override
		protected void fireApplyEditorValue() {
			super.fireApplyEditorValue();
			this.modify.modify();
		}

		@Override
		protected void editOccured(ModifyEvent e) {
			listener.noticeSuccess();
			if (isSave()) {
				super.editOccured(e);
			}
		}

		private boolean isSave() {
			if (currentColumn == 2) {// 对编号的合法性进行判断
				return judgeID();
			}
			if(currentColumn == 3){//对名称是否为空进行判断
				return judgeName();
			}
			return true;
		}

		private boolean judgeName() {
			String str = text.getText();
			if(str == null || str.equals("")){
				listener.noticeFault("错误：货商名称为空，数据不能保存！");
				str = "";
				return false;
			}
			return true;
		}

		@SuppressWarnings("unchecked")
		private boolean judgeID() {
			String str = text.getText();
			List<Hsinfo> list = ExtentionInfo.getInstance().getBusinessInfoList();
			String regex = "[0-9]*";
			if (str != null && !str.equals("")) {
				if (str.matches(regex)) {
					for (int i = 0; i < list.size(); i++) {
						if (!str.equals(oldString)
								&& list.get(i).getHsid().equals(str)) {
							listener.noticeFault("错误：货商编号重复，数据不能保存！");
							str = "";
							text.setToolTipText("编号重复");
							text.setText(str);
							return false;
						}
					}

				} else {
					listener.noticeFault("错误：请输入数字作为货商编号！");
					str="";
					text.setToolTipText("编号非法");
					text.setText(str);
					return false;
				}

			} else {
				listener.noticeFault("错误：请输入正确的品牌编号(非重复的数字编号)！");
				return false;
			}
			text.setToolTipText("");
			return true;
		}

		public String getOldString() {
			return oldString;
		}

		public void setOldString(String oldString) {
			this.oldString = oldString;
		}

}
